//
//  CubeLandingViewController.m
//  bsl-sdk
//
//  Created by Fanty on 13-12-6.
//
//

#import "CubeLandingViewController.h"
#import <chameleon-ios-sdk/ChamleonSDK.h>
#import "CubeModule.h"
#import "CubesModel.h"
#import "DataCenter+Cube.h"
#import "BSLCubeConstant.h"
#import "ImageDownloadedView.h"
#import "CubeModuleManager.h"
#import "LandScroller.h"
#import "IsolatedStorageFile+CubeLogic.h"
#import <MainModuleSDK/MainUtils.h>

@interface CubeLandingViewController ()<UIAlertViewDelegate,ZillaDelegate>
-(void)confirmClick;

-(void)initializeModel;
-(void)initialize:(CubeModel*)cubeModel;
-(void)update:(CubeModel*)model;
-(void)loadSnap:(NSString*)identifier version:(NSString*)version;
-(void)updateNotification;
-(void)cubeAuthSync_Success;
@end

@implementation CubeLandingViewController

- (id)init{
    self = [super init];
    if (self) {
        self.title=@"模块详情";
        
        zillaSDK=[[Zilla alloc] initWithZillAccessData:[ZillaAccessData activeSession]];
        zillaSDK.delegate=self;
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateNotification) name:CubeModuleDownloadingProcess object:nil];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateNotification) name:CubeModuleDownloadingSuccess object:nil];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateNotification) name:CubeModuleDownloadingFailed object:nil];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(cubeAuthSync_Success) name:@"CubeAuthSync_Success" object:nil];
        
    }
    return self;
}

- (void)viewDidLoad{
    [super viewDidLoad];
    
    self.view.backgroundColor=[UIColor whiteColor];
    
    [self initNavigation];
    
    
    float top=20.0f+CGRectGetMaxY(navigationBar.frame);
    
    imageView=[[ImageDownloadedView alloc] initWithFrame:CGRectMake(10.0f, top, 50.0f, 50.0f)];
    
    [self.view addSubview:imageView];
    
    
    
    float left=CGRectGetMaxX(imageView.frame)+10.0f;
    
    titleView=[[UILabel alloc] initWithFrame:CGRectMake(left, top, 220.0f-left, 30.0f)];
    titleView.numberOfLines=1;
    titleView.backgroundColor=[UIColor clearColor];
    titleView.textColor=[UIColor blackColor];
    titleView.font=[UIFont systemFontOfSize:11.0f];
    [self.view addSubview:titleView];
    
    vertionView=[[UILabel alloc] initWithFrame:CGRectMake(left, CGRectGetMaxY(titleView.frame), 220.0f-left, 30.0f)];
    vertionView.numberOfLines=1;
    vertionView.backgroundColor=[UIColor clearColor];
    vertionView.textColor=[UIColor blueColor];
    vertionView.font=[UIFont systemFontOfSize:11.0f];
    [self.view addSubview:vertionView];
    
    descView=[[UILabel alloc] initWithFrame:CGRectMake(left, CGRectGetMaxY(vertionView.frame), self.view.frame.size.width-left-20.0f, 60.0f)];
    descView.numberOfLines=0;
    descView.backgroundColor=[UIColor clearColor];
    descView.textColor=[UIColor blackColor];
    descView.font=[UIFont systemFontOfSize:11.0f];
    [self.view addSubview:descView];
    
    
    UIImage* img=[UIImage imageNamed:@"Module.bundle/images/installbtnbg.png"];
    confirmButton=[UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:confirmButton];
    confirmButton.frame=CGRectMake(self.view.frame.size.width-10.0f-img.size.width*1.5f, top+5.0f, img.size.width*1.5f, img.size.height*1.5f);
    confirmButton.titleLabel.font=[UIFont systemFontOfSize:12.0f];
    [confirmButton setBackgroundImage:img forState:UIControlStateNormal];
    [confirmButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [confirmButton addTarget:self action:@selector(confirmClick) forControlEvents:UIControlEventTouchUpInside];
    
    
    landScroller=[[LandScroller alloc] init];
    
    CGRect rect=landScroller.frame;
    rect.origin.y=CGRectGetMaxY(descView.frame);
    
    rect.size.width=self.view.frame.size.width;
    
    landScroller.frame=rect;
    [self.view addSubview:landScroller];
    
    landDescView=[[UILabel alloc] initWithFrame:CGRectMake(5.0f, CGRectGetMinY(rect)-30.0f, CGRectGetMaxX(imageView.frame), 30.0f)];
    landDescView.text=@"详情";
    landDescView.textAlignment=NSTextAlignmentCenter;
    landDescView.numberOfLines=1;
    landDescView.backgroundColor=[UIColor clearColor];
    landDescView.textColor=[UIColor blackColor];
    landDescView.font=[UIFont systemFontOfSize:13.0f];
    [self.view addSubview:landDescView];
    
    progressView=[[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault];
    progressView.frame=CGRectMake(0.0f, imageView.frame.size.height-25.0f, imageView.frame.size.width, 20.0f);
    [imageView addSubview:progressView];
    
    [self initializeModel];
    
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
}

- (void)didReceiveMemoryWarning{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [zillaSDK cancelAllWorkGroup];
    
}


#pragma mark method

-(void)initializeModel{
    //type 0 未安装  1已安装  2 待更新
    NSArray* models=nil;
    if([[DataCenter defaultCenter] finidInstallCubeModule:self.identifier]==nil){  //未安装
        type=0;
        models = [DataCenter defaultCenter].serviceModules;
        
    }
    else{
        models=[DataCenter defaultCenter].installMoudules;
        type=1;
    }
    
    CubeModel* selectedModel = nil;
    for (CubeModel* model in models){
        if([model.identifier isEqualToString:self.identifier]){
            selectedModel = model;
            break;
        }
    }
    if(type==1){
        CubeModel* serviceModel=[[DataCenter defaultCenter] finidServiceCubeModule:self.identifier];
        if(serviceModel.build>selectedModel.build)
            type=2;
    }
    
    NSString* identifier=selectedModel.identifier;
    NSString* version=selectedModel.version;
    
    [self initialize:selectedModel];
    
    CubeModule* cubeModule=(CubeModule*)[[CApplication sharedApplication] moduleForIdentifier:@"Module"];
    
    selectedModel = [cubeModule.cubeModuleManager findDownloadingCubeModule:self.identifier];
    
    
    
    if(selectedModel!=nil)
        [self update:selectedModel];
    
    [self loadSnap:identifier version:version];
    
}

-(void)backClick{
    [zillaSDK cancelAllWorkGroup];
    [super backClick];
}

-(void)confirmClick{
    [progressView setProgress:0 animated:NO];
    CubeModule* cubeModule=(CubeModule*)[[CApplication sharedApplication] moduleForIdentifier:@"Module"];
    
    if (type == 0)  //未下载
    {
        [cubeModule.cubeModuleManager installModule:self.identifier];
        [confirmButton setTitle:@"安装中" forState:UIControlStateNormal];
        confirmButton.enabled = NO;
        progressView.hidden=NO;
        type=3;
        
    }
    else if (type == 1) //已下载
    {
        UIAlertView* alertView=[[UIAlertView alloc] initWithTitle:@"确定删除此模块？" message:nil delegate:self cancelButtonTitle:@"删除" otherButtonTitles:@"取消", nil];
        [alertView show];
        
    }
    else if (type == 2)   //待更新
    {
        [cubeModule.cubeModuleManager updateModule:self.identifier];
        [confirmButton setTitle:@"安装中" forState:UIControlStateNormal];
        confirmButton.enabled = NO;
        progressView.hidden=NO;
        type=3;
        
    }
}

-(void)initialize:(CubeModel*)_cubeModel{
    
    local=([_cubeModel.local length]>0);
    titleView.text=[NSString stringWithFormat:@"模块标题：%@",_cubeModel.name];
    vertionView.text=[NSString stringWithFormat:@"版本号：%@",_cubeModel.version];
    descView.text=[NSString stringWithFormat:@"应用描述:\n%@",_cubeModel.releaseNote];
    [descView sizeToFit];
    CGRect rect=descView.frame;
    
    NSString* icon=[IsolatedStorageFile outputIcon:_cubeModel];
    if(local){
        icon=[icon stringByReplacingOccurrencesOfString:@"../img/" withString:@"Module.bundle/www/img/"];
        icon=[[NSBundle mainBundle] pathForResource:icon ofType:nil];
        UIImage* img=[UIImage imageWithContentsOfFile:icon];
        imageView.image=img;
        [imageView removeLoading];
    }
    else{
        if([icon rangeOfString:@"http://"].length<1){
            UIImage* img=[[UIImage alloc] initWithContentsOfFile:icon];
            if(img!=nil){
                imageView.image=img;
                [imageView removeLoading];
            }
        }
        else{
            [imageView setUrl:icon];
        }
        
    }
    
    if(rect.size.height>60.0f){
        rect.size.height=60.0f;
        descView.frame=rect;
    }
    
    
    /*
     *  张国东
     *  修改模块详情时， 对安装/删除/更新 按钮 做处理
     */
    if (type == 0)        //未下载
    {
        confirmButton.enabled = YES;
        [confirmButton setTitle:@"安装" forState:UIControlStateNormal];

        confirmButton.hidden=(![[DataCenter defaultCenter] priviligeGetModuleByIdentifier:self.identifier]);

        progressView.hidden=YES;

    }
    else if (type == 1) //已下载
    {
        confirmButton.enabled = YES;
        [confirmButton setTitle:@"删除" forState:UIControlStateNormal];

        confirmButton.hidden=(![[DataCenter defaultCenter] priviligeDeleteModuleByIdentifier:self.identifier]);

        progressView.hidden=YES;
        
    }
    else if (type == 2)   //待更新
    {
        confirmButton.enabled=YES;
        [confirmButton setTitle:@"更新" forState:UIControlStateNormal];

        confirmButton.hidden=(![[DataCenter defaultCenter] priviligeGetModuleByIdentifier:self.identifier]);

        progressView.hidden=YES;

    }
    
    if (local){
        confirmButton.hidden=YES;
        progressView.hidden=YES;
    }
    
}

-(void)update:(CubeModel*)model{
    if (model.status == CubeMoudleStatusNone){
        [confirmButton setTitle:@"安装" forState:UIControlStateNormal];
        confirmButton.enabled = YES;
        progressView.hidden=YES;
        
        confirmButton.hidden=(![[DataCenter defaultCenter] priviligeGetModuleByIdentifier:self.identifier]);
        type=0;
    }
    else if (model.status == CubeMoudleStatusFinish)
    {
        [confirmButton setTitle:@"删除" forState:UIControlStateNormal];
        confirmButton.enabled = YES;
        progressView.hidden=YES;
        
        confirmButton.hidden=(![[DataCenter defaultCenter] priviligeDeleteModuleByIdentifier:self.identifier]);

        
        type=1;
    }
    else if (model.status == CubeMoudleStatusCanUpdate)
    {
        [confirmButton setTitle:@"更新" forState:UIControlStateNormal];
        confirmButton.enabled = YES;
        progressView.hidden=YES;
        confirmButton.hidden=(![[DataCenter defaultCenter] priviligeGetModuleByIdentifier:self.identifier]);

        type=2;
    }
    else
    {
        [confirmButton setTitle:@"安装中" forState:UIControlStateNormal];
        confirmButton.enabled = NO;
        progressView.hidden=NO;

        type=3;
    }
    
    float process=(float)model.downloadedProcess/(float)model.downloadedTotalCount;
    if(process>progressView.progress)
        [progressView setProgress:process animated:NO];
    
    if (local){
        confirmButton.hidden=YES;
        progressView.hidden=YES;
    }

}

-(void)loadSnap:(NSString*)identifier version:(NSString*)version{
    
    [zillaSDK cancelAllWorkGroup];
    
    [zillaSDK snapshot:identifier version:version];
}


#pragma mark zilla SDK delegate
-(void)snapshotSuccess:(NSArray*)list{
    [landScroller setImages:list];
}

-(void)snapshotFailed:(int)statusCode errorMessage:(NSString*)errorMessage{
    
}


-(void)updateNotification{
    NSArray* models=nil;
    models = [DataCenter defaultCenter].installMoudules;
    CubeModel* selectedModel = nil;
    for (CubeModel* model in models){
        if([model.identifier isEqualToString:self.identifier]){
            selectedModel = model;
            break;
        }
    }
    [self update:selectedModel];
    
}

-(void)cubeAuthSync_Success{
    if(![[DataCenter defaultCenter] priviligeGetModuleByIdentifier:self.identifier]){
        [[NSNotificationCenter defaultCenter] removeObserver:self];
        UIAlertView* alertView=[[UIAlertView alloc] initWithTitle:@"你没有模块使用权限" message:nil delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alertView show];
        [self.navigationController popViewControllerAnimated:YES];
        return;
    }
    
    if(type==1){
        confirmButton.hidden=(![[DataCenter defaultCenter] priviligeDeleteModuleByIdentifier:self.identifier]);
    }
    if (local){
        confirmButton.hidden=YES;
        progressView.hidden=YES;
    }

}

#pragma mark alertview delegate

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if(buttonIndex==0){
        CubeModule* cubeModule=(CubeModule*)[[CApplication sharedApplication] moduleForIdentifier:@"Module"];
        [cubeModule.cubeModuleManager uninstallModule:self.identifier];
        [confirmButton setTitle:@"安装" forState:UIControlStateNormal];
        confirmButton.enabled = YES;
        progressView.hidden=YES;
        type=0;
    }
}

@end
